package xgenerator.ui.swing;

import java.awt.Image;
import java.net.URL;

import javax.swing.ImageIcon;

public class IconUtils {
	
	/**
	 * <p>
	 * Title：获取classpath的资源
	 * </p>
	 * @author <a href="mailto:shushanlee@msn.com">liss</a>
	 * @param path
	 * @return
	 */
	private static final URL getClasspathResource(String path) {
		ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
		if(null == classLoader) {
			classLoader = IconUtils.class.getClassLoader();
		}
		if(null != path) {
			if(path.startsWith("classpath*:")) {
				path = path.substring(11);
			}
			if(path.startsWith("classpath:")) {
				path = path.substring(10);
			}
			if(path.startsWith("classpath/")) {
				path = path.substring(10);
			}
		}
		return classLoader.getResource(path);
	}
	
	/**
	 * <p>
	 * Title：创建图标
	 * </p>
	 * @author <a href="mailto:shushanlee@msn.com">liss</a>
	 * @param path
	 * @return
	 */
	public static ImageIcon createImageIcon(String path) {
		ImageIcon imageIcon = null;
		if (null != path && !"".equals(path)) {
			URL url = getClasspathResource(path);
			if (null != url) {
				imageIcon = new ImageIcon(url);
			} else {
				System.err.println("在classpath中查找不到资源：" + path);
			}
		}
		return imageIcon;
	}
	
	/**
	 * <p>
	 * Title：创建title图标image
	 * </p>
	 * @author <a href="mailto:shushanlee@msn.com">liss</a>
	 * @param path
	 * @return
	 */
	public static Image createIconImage(String path) {
		/*
		Image iconImage = null;
		if (null != path && !"".equals(path)) {
			URL url = IconUtils.class.getResource(path);
			if (null != url) {
				return Toolkit.getDefaultToolkit().createImage(url);
			} else {
				System.err.println("找不到图片" + path);
				return null;
			}
		}
		return null;
		*/
		
		ImageIcon imageIcon = createImageIcon(path);
		return null != imageIcon ? imageIcon.getImage() : null;
	}

}
